import { DynamicModule, Module } from '@nestjs/common';
import { ClientsModule, Transport } from '@nestjs/microservices';
import { MicroserviceGatewayController } from './microservice-gateway.controller';
import { MicroserviceGatewayService } from './microservice-gateway.service';

export interface MicroserviceConfig {
  name: string;
  transport: Transport;
  options: {
    host: string;
    port: number;
    [key: string]: any;
  };
  routePrefix?: string;
}

@Module({})
export class MicroserviceGatewayModule {
  static register(msList: MicroserviceConfig[]): DynamicModule {
    var configs =  msList.map((s:MicroserviceConfig) => ({
      name: s.name,
      transport: s.transport,
      options: s.options,
    }));
    var c1 = configs[0];
    return {
      module: MicroserviceGatewayModule,
      imports: [
        ClientsModule.register(
          [c1]
        ),
      ],
      controllers: [MicroserviceGatewayController],
      providers: [
        MicroserviceGatewayService,
        {
          provide: 'MICROSERVICE_CONFIGS',
          useValue: msList,
        },
      ],
      exports: [MicroserviceGatewayService],
    };
  }
}